<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef } from 'vue'
import { ApiResponse } from '@/apis/types/Response'
import { File } from '@/apis/types/File'
import { useVModel } from '@vueuse/core'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { useUserStore } from '@/store/userStore'
import { ElMessage } from 'element-plus'


// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
const props = defineProps({
  value: {
    type: String,
    default: ''
  },
  categoryId: {
    type: Number,
    default: -1
  }
})
const emit = defineEmits(['update:value'])
const valueHtml = useVModel(props, 'value', emit)


type InsertFnType = (url: string, poster?: string) => void  //poster 视频封面
const userStore = useUserStore()
const toolbarConfig = {}
const editorConfig = {
  placeholder: '创作点什么吧...',
  MENU_CONF: {
    uploadImage: {
      server: "/api/ability/file/upload",
      fieldName: "file",
      maxFileSize: 300 * 1024 * 1024,
      maxNumberOfFiles: 10,
      allowedFileTypes: ['image/*'], //[]无限制
      headers: {
        'Goalias-Token': 'Bearer ' + userStore.userInfo?.goaliasToken
      },
      meta: {
        categoryId: props.categoryId
      },
      timeout: 5 * 1000, // 5 秒
      customInsert(res: ApiResponse<File>, insertFn: InsertFnType) {
        // 从 res 中找到 url alt href ，然后插入图片
        if (res.code == 200) {
          ElMessage.success('上传成功')
          insertFn(res.data.fileUrl)
        } else {
          ElMessage.error('上传文件失败:' + res?.msg || 'error')
        }

      },
      onSuccess(file: File, res: ApiResponse<File>) {
        console.log(`${res.data.fileName}上传成功`, )
      },
    },
    uploadVideo: {
      server: "/api/ability/file/upload",
      fieldName: "file",
      maxFileSize: 300 * 1024 * 1024,
      maxNumberOfFiles: 3,
      allowedFileTypes: ['video/*'],
      headers: {
        'Goalias-Token': 'Bearer ' + userStore.userInfo?.goaliasToken
      },
      meta: {
        categoryId: props.categoryId
      },
      timeout: 15 * 1000, // 5 秒
      customInsert(res: ApiResponse<File>, insertFn: InsertFnType) {
        // 从 res 中找到 url alt href ，然后插入图片
        if (res.code == 200) {
          insertFn(res.data.fileUrl)
          ElMessage.success('上传成功')
        } else {
          ElMessage.error('上传文件失败:' + res?.msg || 'error')
        }

      },
    }
  }

}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

defineExpose({
  getHtml: () => {
    return editorRef.value.getHtml()
  },
  setHtml: (html: string) => {
    editorRef.value.setHtml(html)
  },
  getElemsByType: (type: string)=>{ //image、video、link
    return editorRef.value.getElemsByType(type)
  }
})


</script>

<template>
  <div class="text-editor">
    <Toolbar class="toolbar" :editor="editorRef" :defaultConfig="toolbarConfig" />
    <Editor  style="height: 500px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig"
      @onCreated="handleCreated" />
  </div>
</template>

<style scoped>
.text-editor {
  border: 10px solid #409EFF;
  border-radius: 20px;
  transition: all 0.5s ease;
  padding: 3px;
}

.text-editor:hover {
  border-color: #ff80f0;
}

.toolbar {
  border-bottom: 1px solid #ccc;
}
.w-e-full-screen-container {
  z-index: 100 !important;
}
</style>
